package org.mao.coque.interceptor;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

public class CoqueHandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

        // 解决The extension [x-webkit-deflate-frame] is not supported问题
        if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
            request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
        }

        System.out.println("Before Handshake");

        ServletServerHttpRequest httpRequest = (ServletServerHttpRequest) request;
        HttpSession httpSession = httpRequest.getServletRequest().getSession();
        System.out.println(httpSession.getAttribute("nickName"));
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        System.out.println("After Handshake");
        ServletServerHttpRequest httpRequest = (ServletServerHttpRequest) request;
        HttpSession httpSession = httpRequest.getServletRequest().getSession();
        System.out.println(httpSession.getAttribute("nickName"));
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
